package testing_package;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Title:        Sample Server
 * Description:  This utility will accept input from a socket, posting back to the socket before closing the link.
 * It is intended as a template for coders to base servers on. Please report bugs to brad at kieser.net
 * Copyright:    Copyright (c) 2002
 * Company:      Kieser.net
 * @author B. Kieser
 * @version 1.0
 */

public class Sample_server {

  private static int port=4444, maxConnections=0;
  private static int counter = 0;
  private static Thread T = null;
  // Listen for incoming connections and handle them
  public static void main(String[] args) {
    int i=0;

    try{
      ServerSocket listener = new ServerSocket(port);
      Socket server;

      while((i++ < maxConnections) || (maxConnections == 0)){
        doComms connection;

        server = listener.accept();        
        doComms conn_c= new doComms(server, counter++);
        Thread t = new Thread(conn_c);
        if (T == null)
        	T = t;
        else
        	T.notify();
        t.start();
        t.wait();
        System.out.println("Running");
      }
    } catch (IOException ioe) {
      System.out.println("IOException on socket listen: " + ioe);
      ioe.printStackTrace();
    } catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
  }

}

class doComms extends Thread {
    private Socket server;
    private String line,input;
    private int counter;
    private static boolean allowWait = true;

    doComms(Socket server, int counter) {
      this.server=server;
      this.counter = counter;
    }

    public void run () {

      
      input="";

      try {
        // Get input from the client
    	BufferedReader in = new BufferedReader (new InputStreamReader(server.getInputStream()));
        PrintStream out = new PrintStream(server.getOutputStream());

        while((line = in.readLine()) != null && !line.equals(".")) {
          input=input + line;
          out.println("I got:" + line);
        }
        
        //if (input.equals("ping"))
        //	this.notifyAll();
        //else
        //	Thread.currentThread().sleep(4000);
       
        // Now write to the client        
        System.out.println(counter + " Overall message is:" + input);
        out.println("Overall message is:" + input);
        server.close();
                
      } catch (IOException ioe) {
        System.out.println("IOException on socket listen: " + ioe);
        ioe.printStackTrace();
      } 
    }
}